package com.bwie.bwedu.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bwie.bwedu.R;
import com.bwie.bwedu.bean.Student;
import com.bwie.bwedu.bean.Version;
import com.bwie.bwedu.fragment.InvalidFragment;
import com.bwie.bwedu.fragment.LocalSaveFragment;
import com.bwie.bwedu.fragment.TrackFragmen;
import com.bwie.bwedu.fragment.WaittingConfirmFragment;
import com.bwie.bwedu.net.CustomerHttpClient;
import com.bwie.bwedu.net.HttpUtils;
import com.bwie.bwedu.presenter.impl.GetDaiLiImpl;
import com.bwie.bwedu.ui.dialog.CustomBaseDialog;
import com.bwie.bwedu.utils.ASimpleCacheUtils;
import com.bwie.bwedu.utils.ToastUtils;
import com.bwie.bwedu.utils.VersionUtil;
import com.bwie.bwedu.view.AgentView;
import com.bwie.bwedu.volley.RequestAPI;

import org.apache.http.HttpEntity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;

public class MainActivity extends BaseActivity implements AgentView{

	private int currentX;
	private int currentIndex;
    private WaittingConfirmFragment wait;
    private TrackFragmen track;
    private LocalSaveFragment save;
    private InvalidFragment invalid;
    private FragmentManager manager;
	private RadioButton main_waitaffirm;
	private RadioButton main_track;
	private RadioButton main_savelocal;
	private RadioButton main_invalidinfo;
	private ImageView mian_person;
	private ImageView main_add;
	private ImageView main_buttom_img;
	private RadioGroup homeGroup;
	private SharedPreferences sp;
	private SharedPreferences.Editor edit;
	private CustomBaseDialog dialog;
	private Version ver;

	@Override
	public int getLayout() {
		return R.layout.activity_main;
	}

	@Override
	public void findView() {
		main_waitaffirm = (RadioButton) findViewById(R.id.main_waitaffirm);
		main_track = (RadioButton) findViewById(R.id.main_track);
		main_savelocal = (RadioButton) findViewById(R.id.main_savelocal);
		main_invalidinfo = (RadioButton) findViewById(R.id.main_invalidinfo);
		mian_person = (ImageView) findViewById(R.id.main_personal);
		main_add = (ImageView) findViewById(R.id.main_add);
		main_buttom_img = (ImageView) findViewById(R.id.main_buttom_img);
		homeGroup = (RadioGroup) findViewById(R.id.main_ll);



	}

	@Override
	public void setData() {
	String no=ASimpleCacheUtils.read("no");
		if(TextUtils.isEmpty(no)) {
			SystemClock.sleep(1000);
				//提示上拉刷新
				dialog = new CustomBaseDialog(this);
				dialog.show();
				dialog.setText("上划可以查看更多数据，"+"\n"+"下划可以查看最新数据");
				dialog.chbeckoxstae(View.VISIBLE);
				dialog.setListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if(dialog.chbeckox()){
							ASimpleCacheUtils.write("no", "no");
							showToast("一定记得划动哦~");
						}
						dialog.cancel();
					}
				});
		}

		//初始化图片宽度
		ViewGroup.LayoutParams params = main_buttom_img.getLayoutParams();
		params.width=(getWindowManager().getDefaultDisplay().getWidth())/4;
		main_buttom_img.setLayoutParams(params);
		currentX=main_waitaffirm.getLeft();
		//待确认
		wait = new WaittingConfirmFragment();
		//跟踪
		track = new TrackFragmen();
		//本地保存
		save = new LocalSaveFragment();
		//无效信息
		invalid = new InvalidFragment();

		manager = getSupportFragmentManager();
		FragmentTransaction transaction = manager.beginTransaction();

		transaction.add(R.id.main_fl, wait, "wait");
		transaction.add(R.id.main_fl, track, "track");
		transaction.add(R.id.main_fl, save, "save");
		transaction.add(R.id.main_fl, invalid, "invalid");

		transaction.commit();

		switchFragment(0);

		// TODO diaoyong请求json接口，presenter里面没有专门实现类，最好抽出以前Add专门实现
		GetDaiLiImpl getDaiLi = new GetDaiLiImpl(this);
		sp = getSharedPreferences("dailiinfo",MODE_PRIVATE);

//		TODO SharedPreferences.Editor edit = sp.edit();
//
		if(sp.getBoolean("first",true)){
			//  转移至main
			getDaiLi.getDaili();
		} else {
			if(HttpUtils.isWifiConnected(MainActivity.this)){
				// 将读取下来的json进行本地存储存储

				getDaiLi.getDaili();


			} else {
				ToastUtils.getToast("当前无线网络不可用，将在可用时为您更新最新数据");
			}
		}
	}

	@Override
	public void setListener() {
//		main_waitaffirm.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				switchFragment(0);
//			}
//		});
//
//		main_track.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				switchFragment(1);
//			}
//		});
//
//		main_savelocal.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				switchFragment(2);
//			}
//		});
//
//		main_invalidinfo.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				switchFragment(3);
//			}
//		});

		homeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {

					int position=0;
					switch (checkedId){
						case R.id.main_waitaffirm:
							position=0;
							break;
						case R.id.main_track:
							position=1;
							break;
						case R.id.main_savelocal:
							position=2;
							break;
						case R.id.main_invalidinfo:
							position=3;
							break;
					}
					TranslateAnimation animation = new TranslateAnimation(
							currentX ,
							((RadioButton) homeGroup.getChildAt(position)).getLeft(), 0f, 0f);
					animation.setInterpolator(new LinearInterpolator());
					animation.setDuration(100);
					animation.setFillAfter(true);

					//执行位移动画
					main_buttom_img.startAnimation(animation);

					switchFragment(position);  //ViewPager 跟随一起 切换

					//记录当前 下标的距最左侧的 距离
					currentX = ((RadioButton) homeGroup.getChildAt(position)).getLeft();

				}
		});
		mian_person.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, PersonalActivity.class));
				overridePendingTransition(R.anim.leftenter,R.anim.rightexit);
				ToastUtils.getToast("个人主页");
			}
		});

		main_add.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(MainActivity.this, StudentInfoActivity.class),100);
//				startActivity(new Intent(MainActivity.this, StudentInfoActivity.class));
				overridePendingTransition(R.anim.rightenter,R.anim.leftexit);
				ToastUtils.getToast("添加学员");
			}
		});

	}

	private void switchFragment(int j) {
        Fragment[] fr = new Fragment[]{wait,track,save,invalid};
        FragmentTransaction transaction = manager.beginTransaction();
        for (int i = 0; i < fr.length; i++){
			if (j<currentIndex){
				transaction.setCustomAnimations(R.anim.leftenter,R.anim.rightexit);
			}else if (j>currentIndex){
				transaction.setCustomAnimations(R.anim.rightenter,R.anim.leftexit);
			}
            if (i == j){
                transaction.show(fr[i]);
            }else {
                transaction.hide(fr[i]);
            }
        }
		currentIndex=j;
		transaction.commit();
    }


		/**
		 *  switch (v.getId()){
		 case R.id.main_waitaffirm:
		 switchFragment(0);
		 break;
		 case R.id.main_track:
		 switchFragment(1);
		 break;
		 case R.id.main_savelocal:
		 switchFragment(2);
		 break;
		 case R.id.main_invalidinfo:
		 switchFragment(3);
		 break;
		 case R.id.mian_person:
		 startActivity(new Intent(this, PersonalActivity.class));
		 ToastUtils.getToast("个人主页");
		 break;
		 case R.id.main_add:
		 startActivity(new Intent(this, StudentInfoActivity.class));
		 ToastUtils.getToast("添加学员");
		 break;
		 }
		 */

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ASimpleCacheUtils.remove("tk");
		ASimpleCacheUtils.remove("username");
	}

	@Override
	public void onSuccess(String info) {

		if (sp.getBoolean("first",true)){
			ASimpleCacheUtils.write("dailirenhuancun",info);
			edit = sp.edit();
			edit.putBoolean("first",false);
		} else {
			if (!TextUtils.isEmpty(info)){
				ASimpleCacheUtils.write("dailirenhuancun",info);
				edit.putBoolean("first",false);
			}else{
				return;
			}
		}
	}

	public void addList(Student student,int tag){
		switch (tag){
			case 1:
				track.addList(student);
				break;
			case 2:
				save.addList(student);
				break;
			case 3:
				invalid.addList(student);
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode==100&&resultCode==300){
			Student stu = (Student) data.getSerializableExtra("stu");
			stu.flag="2";
			addList(stu,2);
		}else if(requestCode==100&&resultCode==400){
			Student stu = (Student) data.getSerializableExtra("stu");
			addList(stu,2);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onFail() {
		ToastUtils.getToast("请确认网络连接");
	}

	private void checkVersion() {
		String path = getResources().getString(R.string.upd_url);
		RequestAPI.getVersion(path, new Response.Listener<String>() {
			@Override
			public void onResponse(String s) {
				ver = VersionUtil.getVersion(s);
				String version = ver.getVersion();
				int versionCode = 0;
				try {
					versionCode =getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
				} catch (PackageManager.NameNotFoundException e) {

					e.printStackTrace();
				}
				if (versionCode < Integer.parseInt(version)) {
					final CustomBaseDialog dialog=new CustomBaseDialog(MainActivity.this);
					dialog.show();
					dialog.setText("是否升级新版本？");
					dialog.setButton("立刻升级","暂不升级");
					dialog.setListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.dismiss();
							loadApk();
						}
					});
				}
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError volleyError) {

			}
		});
	}
	private void loadApk() {
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载");
		pd.show();
		new Thread() {
			public void run() {
				HttpEntity entity = CustomerHttpClient.getEntity(ver.getUrl());
				pd.setMax((int) entity.getContentLength());
				File file = new File(Environment.getExternalStorageDirectory(),
						"upd.apk");
				try {
					if (!file.exists()) {
						file.createNewFile();
					}
					FileOutputStream fos = new FileOutputStream(file);
					int len=0;
					int total=0;
					byte[] b=new byte[1024];
					BufferedInputStream bis=new BufferedInputStream(entity.getContent());
					while ((len=bis.read(b))!=-1) {
						fos.write(b, 0, len);
						total+=len;
						pd.setProgress(total);
					}
					pd.cancel();
					VersionUtil.installApk(file, MainActivity.this);
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							showToast("升级完成");
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	};
}
